package andy.ham;

import java.text.DateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import andy.ham.DaoMaster.DevOpenHelper;
import android.app.Dialog;
import android.os.Bundle;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.widget.Toast;

public class DiaryEditor extends Activity {

	private static final String TAG = "Diary";
	public static final String EDIT_DIARY_ACTION = "andy.ham.DiaryEditor.EDIT_DIARY";
	public static final String INSERT_DIARY_ACTION = "andy.ham.DiaryEditor.action.INSERT_DIARY";
	public static final int MENU_ITEM_DELETE = Menu.FIRST + 1;

	/**
	 * 查询cursor时候，感兴趣的那些条例。
	 */

	private SQLiteDatabase db;

	private DaoMaster daoMaster;
	private DaoSession daoSession;
	private NoteDao noteDao;
	private Note note;
	private Cursor cursor;

	private static final int STATE_EDIT = 0;
	private static final int STATE_INSERT = 1;
	private String dUriString;
	private int mState;
	private Uri mUri;
	private Cursor mCursor;
	private EditText mTitleText;
	private EditText mBodyText;
	private Button confirmButton;
	private Button shareBtu;
	private Button back;
	private long mid;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		final Intent intent = getIntent();
		final String action = intent.getAction();
		setContentView(R.layout.diary_edit);

		mTitleText = (EditText) findViewById(R.id.title);
		mBodyText = (EditText) findViewById(R.id.body);
		confirmButton = (Button) findViewById(R.id.confirm);
		shareBtu=(Button)findViewById(R.id.share);
		back=(Button)findViewById(R.id.back);

		initDAO();//初始化
		Log.d("action", action);

		if (EDIT_DIARY_ACTION.equals(action)) {// 编辑日记

			Bundle bundle = new Bundle();
			bundle = this.getIntent().getExtras();
			mid = bundle.getLong("id");

			note = noteDao.loadByRowId(mid);

			/**然后取出“正文”字段，这时有一个比较有趣的技巧，“设置文本”并不是调用setText，
			 * 而是调用的setTextKeepState，后者相对于前者有一个优点，
			 * 就是当界面此前stop掉，现在重新resume回来，那么此前光标所在位置仍然得以保存。
			 * 而若使用setText，则光标会重置到行首*/
			mTitleText.setTextKeepState(note.getTitle());
			mBodyText.setTextKeepState(note.getBody());

			// setResult(RESULT_OK, (new Intent()).setAction(mUri.toString()));
			setTitle("编辑日记");
		} else if (INSERT_DIARY_ACTION.equals(action)) {// 新建日记
			mState = STATE_INSERT;
			setTitle("新建日记");
		} else {
			Log.e(TAG, "no such action error");
			finish();
			return;
		}

		confirmButton.setOnClickListener(new View.OnClickListener()
		{
			public void onClick(View view) {
				if (mState == STATE_INSERT) {
					insertDiary();
				} else {
					updateDiary();
				}
				Intent intent = new Intent(DiaryEditor.this, LifeDiary.class);
				startActivity(intent);
				DiaryEditor.this.finish();
			}
		});

		/**分享现在有许多集成的，如友盟，ShareSDK等，或者直接去下载哪个App的分享SDK来集成，
		 * 这些分享都是会提示来自xxx(appName)。
		 * 如果不需要，可以简单通过Intent.ACTION_SEND来实现分享功能
		 *
		 * 分享纯文本
		 * 如上面，调用ShareUtil.share(this, "test share");就实现了分享文本
		 *
		 * https://blog.csdn.net/xuie0000/article/details/50604741
		 * https://www.cnblogs.com/daner1257/p/5581443.html
		 * */
		shareBtu.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent intent1=new Intent(Intent.ACTION_SEND);
				/**用Intent.EXTRA_STREAM来标志附加的消息类型
				 * 如果是文字的话原理是一样的，只需将Type和附加信息改成
				 * intent.setType("text/plain");
				 * intent.putExtra(Intent.EXTRA_TEXT,"hello world");*/
				intent1.putExtra(Intent.EXTRA_TEXT,mBodyText.getText().toString());
				intent1.setType("text/plain");
				startActivity(Intent.createChooser(intent1,"分享"));
			}
		});

		back.setOnClickListener(new View.OnClickListener(){
			public void onClick(View view){
				Builder dialog=new AlertDialog.Builder(DiaryEditor.this);
				dialog.setTitle("看到这个提示没有");// 可写在strings里面
				dialog.setMessage("要不要返回？");

				DialogInterface.OnClickListener dialogOnclickListener=new DialogInterface.OnClickListener(){
					@Override
					public void onClick(DialogInterface dialog,int which)
					{
						switch(which){
							case Dialog.BUTTON_POSITIVE:
								Toast.makeText(DiaryEditor.this,"已确定",Toast.LENGTH_SHORT).show();
								Intent intent2 = new Intent(DiaryEditor.this, LifeDiary.class);
								startActivity(intent2);
								DiaryEditor.this.finish();
								break;
							case Dialog.BUTTON_NEGATIVE:
								Toast.makeText(DiaryEditor.this,"已取消",Toast.LENGTH_SHORT).show();
								break;
							case Dialog.BUTTON_NEUTRAL:
								Toast.makeText(DiaryEditor.this,"已忽略",Toast.LENGTH_SHORT).show();
						}
					}
				};

				dialog.setPositiveButton("回去",dialogOnclickListener);
				dialog.setNegativeButton("不回去",dialogOnclickListener);
				dialog.setNeutralButton("不管了",dialogOnclickListener);

				/**创建对话框*/
				dialog.create();
				/**显示对话框*/
				dialog.show();
			}
		});

	}

	/**初始化*/
	private void initDAO() {
		DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes-db",
				null);
		db = helper.getWritableDatabase();
		daoMaster = new DaoMaster(db);
		daoSession = daoMaster.newSession();
		noteDao = daoSession.getNoteDao();
	}

	private void insertDiary() {
		/**用于获取布局中对应编辑框中的内容和当前系统事件*/
		String title = mTitleText.getText().toString();
		if(title.equals(""))
		{
			title="无标题";
		}
		String body = mBodyText.getText().toString();
		final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
				DateFormat.MEDIUM);
		String date = df.format(new Date());

		/**初始化并赋值一个Note变量*/
		Note note = new Note(null, title, body, date);
		/**对数据库进行插入操作只需要调用noteDao类中的insert()方法即可*/
		noteDao.insert(note);

		Log.d("DaoExample", "Inserted new note, ID: " + note.getId());

	}

	private void updateDiary() {
		String title = mTitleText.getText().toString();
		String body = mBodyText.getText().toString();
		final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
				DateFormat.MEDIUM);
		String date = df.format(new Date());

		/**更新日记*/
		Note note = new Note(mid, title, body, date);
		noteDao.insertOrReplace(note);
	}

	// 添加菜单键选项
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(Menu.NONE, MENU_ITEM_DELETE, 0, R.string.menu_delete);
		return true;
	}

	// 添加选择菜单的选择事件
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			// 删除当前数据
			case MENU_ITEM_DELETE:
				// getContentResolver().delete(dUri, null, null);
				/**删除日记*/
				noteDao.deleteByKey(mid);

				Toast.makeText(DiaryEditor.this, R.string.diary_delete_success,
						Toast.LENGTH_LONG).show();
				Intent intent = new Intent(DiaryEditor.this, LifeDiary.class);
				startActivity(intent);
				DiaryEditor.this.finish();
				break;
		}
		return super.onOptionsItemSelected(item);
	}

}
